//
//  WDPNewWebView.m
//  WDLoanSDK
//
//  Created by wujianrong on 2017/8/3.
//  Copyright © 2017年 wanda. All rights reserved.
//

#import "ICENewWebView.h"
#import "ICECore.h"
#import "ICEJavaScriptBridge.h"
#import "ICENavigatorBar.h"
#import "ICEUI.h"

@interface ICENewWebView ()<WKNavigationDelegate>
{
    ICEWebViewProgressBar *_progressBar;
}
@property (nonatomic, strong) UIActivityIndicatorView *titleLoadingIndicator;
@end

@implementation ICENewWebView
-(instancetype)init
{
    self = [super init];
    if (self) {
        _backAction = 1;
        _webTitle = NSLocalizedString(@"加载中", nil);
    }
    return self;
}

- (void)setUrl:(NSURL *)url {
    //[temp addObject:@"kgw_sid=*"];
    
    //入参必须修改
    NSString *sUrl = [url absoluteString];
    if (ICESafeString(sUrl).length == 0) {
        _url = nil;
        
        return;
    }
    
    NSMutableString* string = [[NSMutableString alloc]initWithString:sUrl];
    
    NSURL* tempUrl = [[NSURL alloc]initWithString:string];
    _url = tempUrl;
//    if (self.url && [_vc isViewLoaded]) {
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            NSURLRequest *request =[NSURLRequest requestWithURL:_url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
//            [_webView loadRequest:request];
//        });
//    }
}

-(void)loadNewRequestWithUrl:(NSString*)url
{
    if (ICESafeString(url).length == 0) {
        return;
    }
//    NSURLRequest *request =[NSURLRequest requestWithURL:[[NSURL alloc]initWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
//    [_webView loadRequest:request];
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[[NSURL alloc]initWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
    
    [request setValue:[self getOldCookies:[self.url absoluteString]] forHTTPHeaderField:@"Cookie"];
    [_webView loadRequest:request];
}

-(NSString*)agentString
{
    return [[EMNetConfig sharedConfig] agentString];
}


-(void)webBack
{
    
    if (_webView) {
        if ([_webView canGoBack] == YES) {
            [_webView goBack];
        }
        else
        {
            [self closeWebAction];
        }
        
    }
}

-(void)closeWebAction
{
    [_vc closeWebAction];
}

-(void)refreshWebView
{
    if (_webView) {
        [self updateWebViewCookie];
        [_webView reload];
    }
}

- (UIActivityIndicatorView *)titleLoadingIndicator {
    if (!_titleLoadingIndicator) {
        _titleLoadingIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _titleLoadingIndicator.frame = CGRectMake(0, 0, 20, 20);
    }
    return _titleLoadingIndicator;
}

-(NSString*)getOldCookies:(NSString*)url
{
    if (ICESafeString(url).length <= 0) {
        return nil;
    }
    NSArray *tmp = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:url]];
    NSString* token = nil;
    for (NSHTTPCookie * cookie in tmp) {
        if ([cookie.name isEqualToString:@"accessToken"]) {
            token = cookie.value;
            break;
        }
    }
    
    if (ICESafeString(token).length <= 0) {
        return nil;
    }
    NSString* js = [NSString stringWithFormat:@"accessToken=%@;path=/;domain=%@;httponly", token, [[NSURL URLWithString:url]host]];
    return js;
}

- (NSString *)da_javascriptString:(NSHTTPCookie*)cookie
{
    NSString *string = [NSString stringWithFormat:@"%@=%@;domain=%@;path=%@",
                        cookie.name,
                        cookie.value,
                        cookie.domain,
                        cookie.path ?: @"/"];
    if (cookie.secure) {
        string = [string stringByAppendingString:@";secure=true"];
    }
    return string;
}

- (void)updateWebViewCookie
{
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[self cookieString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    //添加Cookie
    [_webView.configuration.userContentController addUserScript:cookieScript];
}

- (NSString *)cookieString
{
    NSMutableString *script = [NSMutableString string];
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        // Skip cookies that will break our script
        if ([cookie.value rangeOfString:@"'"].location != NSNotFound) {
            continue;
        }
        // Create a line that appends this cookie to the web view's document's cookies
        [script appendFormat:@"document.cookie='%@'; \n", [self da_javascriptString:cookie]];
    }
    return script;
}

-(WKWebViewConfiguration*)getUserConfig
{
    WKUserContentController* userContentController = WKUserContentController.new;
    
//    NSArray *tmp = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
//
//    WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource: [NSString stringWithFormat:@"document.cookie = '%@';", [self getOldCookies:@""]] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
//    [userContentController addUserScript:cookieScript];
    WKWebViewConfiguration* webViewConfig = WKWebViewConfiguration.new;
    webViewConfig.userContentController = userContentController;
    return webViewConfig;
}

- (void)beginBrowse {
    
    
    
    if (_webView == nil) {
        _webView = [[WKWebView alloc]initWithFrame:self.bounds configuration:[self getUserConfig]];
        
    }
    
    [self updateWebViewCookie];
    
    
    _webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:_webView];
    _webView.navigationDelegate = self;
    _webView.allowsBackForwardNavigationGestures = YES;
    _webView.backgroundColor = [UIColor whiteColor];
    
   // [_vc leftNavigationItemWithObject:@"关闭" right:nil title:nil];
    
    UIBarButtonItem *loadingBar = [[UIBarButtonItem alloc] initWithCustomView:self.titleLoadingIndicator];
    _vc.navigationItem.rightBarButtonItem = loadingBar;

    if (_userAgent) {
        _webView.customUserAgent = _userAgent;
    }
    if (self.url) {
        NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:self.url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
        
        [request setValue:[self getOldCookies:[self.url absoluteString]] forHTTPHeaderField:@"Cookie"];
        [_webView loadRequest:request];
    } else if (self.loadContent) {
        [_webView loadHTMLString:self.loadContent baseURL:nil];
    }
    
    _progressBar = [[ICEWebViewProgressBar alloc] init];
    [self addSubview:_progressBar];
    [_progressBar iceModifyY:ICE_VT(self.webView) + _vc.navigationController.navigationBar.shadowImage.size.height];
    [_progressBar startAnimation];
  
}

- (void)handleMessage:(NSDictionary *)param plugin:(NSString*)plugin
{
    NSString* method = [param objectForKey:@"method"];
    NSString* callbackId = [param objectForKey:@"callbackid"];
    NSMutableDictionary* dit = [[NSMutableDictionary alloc]initWithDictionary:param];
    [dit removeObjectForKey:@"method"];
    [dit removeObjectForKey:@"callbackid"];
    
    ICEWebInfo* info = [[ICEWebInfo alloc]init];
    info.vc = _vc;
    info.webView = self;
    [ICEJavaScriptBridge processJSWithPlugin:plugin method:method param:dit vcinfo:info callbackId:callbackId];
    
}

- (NSString *)jsScheme {
    return @"js://";
}

#pragma mark - WKNavigationDelegate

// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation
{
    [self.titleLoadingIndicator setHidden:YES];
    [self.titleLoadingIndicator stopAnimating];
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation
{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    [_webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
        if (ICESafeString(title).length > 0) {
            [self.vc leftNavigationItemWithObject:nil right:nil title:title];
        }
    }];
    [_progressBar finishAnimation];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation
{
    [_progressBar finishAnimation];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    
    if ([navigationAction.request.URL.absoluteString hasPrefix:[self jsScheme]]) {
        [self handleMessage:[navigationAction.request.URL.query parseUrlQuery] plugin:[navigationAction.request.URL host]];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
   // decisionHandler(WKNavigationActionPolicyAllow);
    
    
    NSString *cookie = [self getOldCookies:navigationAction.request.URL.absoluteString];
    // 如果请求头部不包含cookie值则需要我们去传cookie
    if ([navigationAction.request allHTTPHeaderFields][@"Cookie"] && [[navigationAction.request allHTTPHeaderFields][@"Cookie"] rangeOfString:cookie].length > 0) {
        decisionHandler(WKNavigationActionPolicyAllow);
    } else {
        if (ICESafeString(cookie).length <= 0) {
            decisionHandler(WKNavigationActionPolicyAllow);
        }
        else
        {
            if ([navigationAction.request isKindOfClass:[NSMutableURLRequest class]]) {
                NSMutableURLRequest* req = (NSMutableURLRequest*)navigationAction.request;
                [req setValue:cookie forHTTPHeaderField:@"Cookie"];
                decisionHandler(WKNavigationActionPolicyAllow);
                return;
            }
            else
            {
                NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:navigationAction.request.URL];
                [request setValue:cookie forHTTPHeaderField:@"Cookie"];
                [webView loadRequest:request];
                decisionHandler(WKNavigationActionPolicyCancel);
            }
            
        }
    }
   
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
